package cn.com.dcsgo.config;

import cn.com.dcsgo.controller.OtherController;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * MvcConfig
 *
 * @author Dcsgo
 * @since 2025/3/5 8:36
 */
@EnableWebMvc
@Configuration
@ComponentScan({"cn.com.dcsgo.controller"})
public class MvcConfig implements WebMvcConfigurer {

    /**
     * 添加拦截器
     *
     * @param registry registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //拦截所有请求
        //registry.addInterceptor(new MyHandlerInterceptor());

        //指定拦截路径和排除拦截路径
        registry.addInterceptor(new MyHandlerInterceptor())
                .addPathPatterns("/**")//链式调用 支持支持正则表达式 add就是添加拦截路径 *匹配单层路径 **匹配多层路径
                .excludePathPatterns("/exception/**");//exclude就是排除拦截路径 (拦截路径要包含排除拦截的路径,你都拦截不到的排除也没意义)

        //多个拦截器就多调几次addInterceptor方法即可
        //先添加的拦截器会包裹后添加的拦截器(先添加的拦截器的preHandle方法先执行，postHandle、afterCompletion方法后执行)
        //底层是通过 顺序遍历添加的拦截器和逆序遍历来实现的
        registry.addInterceptor(new OtherHandlerInterceptor());
        /*
         * MyHandlerInterceptor.preHandle
         * OtherHandlerInterceptor.preHandle
         * OtherHandlerInterceptor.postHandle
         * MyHandlerInterceptor.postHandle
         * OtherHandlerInterceptor.afterCompletion
         * MyHandlerInterceptor.afterCompletion
         */
        //可以查看源码DispatcherServlet.doDispatch()了解更多
    }
}
